package org.tgcloud.group.service.manager.project;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tgcloud.group.core.APPResultMessage;
import org.tgcloud.group.core.DateUtil;
import org.tgcloud.group.core.ResultMessage;
import org.tgcloud.group.core.StringUtil;
import org.tgcloud.group.entity.MjNormalUser;
import org.tgcloud.group.entity.ProjectIntendedMedia;
import org.tgcloud.group.repository.*;
import org.tgcloud.group.web.controller.dto.meidaParty.MediaPartyDTO;
import org.tgcloud.group.web.controller.dto.project.IntendedMedia.AppIntendedMediaProjectDTO;
import org.tgcloud.group.web.controller.dto.project.IntendedMedia.AppMediaExportDTO;
import org.tgcloud.group.web.controller.dto.project.IntendedMedia.AppMediaListDTO;
import org.tgcloud.group.web.controller.dto.project.IntendedMedia.ProjectIntendedMediaDTO;
import org.tgcloud.group.web.controller.req.project.intendedMedia.AppIntendedMediaExportReq;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: zhy
 * @Created: 2025-08-26-下午4:04
 * @Description:
 */
@Service
public class ProjectIntendedMediaManageService {

    @Autowired
    private ProjectIntendedMediaMapper projectIntendedMediaMapper;

    @Autowired
    private SysLabelValueMapper sysLabelValueMapper;

    @Autowired
    private MjNormalUserMapper normalUserMapper;

    @Autowired
    private MjMediumOfflineMapper mediumOfflineMapper;
    @Autowired
    private MediaMapper mediaMapper;

    @Autowired
    private MjMediaPartyMapper mediaPartyMapper;

    public APPResultMessage<Object, ProjectIntendedMediaDTO> getProjectIntendedMediaList(Integer pageNum, Integer pageSize, Integer projectId, Short status, Short expiredType,
                                                                               Long auditStartTime, Long auditEndTime, String mediumName, String roleIds) {
        if (pageNum != null && pageSize != null){
            PageHelper.startPage(pageNum, pageSize);
            List<ProjectIntendedMediaDTO> list = projectIntendedMediaMapper.selectManageListByKeyword(projectId, status, expiredType,
                    auditStartTime != null ? new Date(auditStartTime) : null, auditEndTime != null ? new Date(auditEndTime) : null,
                    mediumName);
            PageInfo<ProjectIntendedMediaDTO> tables = new PageInfo<>(list);
            for (ProjectIntendedMediaDTO dto : tables.getList()){
                if (StringUtil.isBlank(roleIds) || StringUtil.containsString(roleIds.split(","), "40")){
                    dto.setAuditPerson("******");
                }
            }
            ResultMessage result = ResultMessage.builder().setList(tables.getList()).setAllPageNumber(tables.getPages()).setCount(tables.getTotal());
            APPResultMessage<Object, ProjectIntendedMediaDTO> message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        }else {
            List<ProjectIntendedMediaDTO> list = projectIntendedMediaMapper.selectManageListByKeyword(projectId, status, expiredType,
                    auditStartTime != null ? new Date(auditStartTime) : null, auditEndTime != null ? new Date(auditEndTime) : null,
                    mediumName);
            for (ProjectIntendedMediaDTO dto : list){
                if (StringUtil.isBlank(roleIds) || StringUtil.containsString(roleIds.split(","), "40")){
                    dto.setAuditPerson("******");
                }
            }
            ResultMessage result = ResultMessage.builder().setList(list);
            APPResultMessage<Object, ProjectIntendedMediaDTO> message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        }
    }


    public void doAddIntendedMedia(String[] mediumIds, Integer projectId, boolean isAutomatic){
        // 优先查询该项目下是否存在有效的报备媒体，如果有，那么沿用之前的审核状态、审核时间以及审核理由
        List<ProjectIntendedMedia> projectIntendedMediaList = projectIntendedMediaMapper.selectListByProjectIdAndMediumIds(projectId, mediumIds);
        if (projectIntendedMediaList.isEmpty() || !isAutomatic){
            projectIntendedMediaMapper.insertBatch(mediumIds, projectId);
        } else {
            // 优先处理有效的报备媒体
            List<ProjectIntendedMedia> mediaList = new ArrayList<>();
            for (ProjectIntendedMedia projectIntendedMedia : projectIntendedMediaList){
                ProjectIntendedMedia intendedMedia = projectIntendedMedia;
                intendedMedia.setCreateTime(new Date());
                intendedMedia.setId(null);
                mediaList.add(intendedMedia);
            }
            projectIntendedMediaMapper.insertOldMsgBatch(mediaList);
            List<String> collect = projectIntendedMediaList.stream().map(item -> String.valueOf(item.getMediumId())).collect(Collectors.toList());
            String[] newMediumIds = StringUtil.removeElementsByList(mediumIds, collect);
            if (newMediumIds.length > 0){
                projectIntendedMediaMapper.insertBatch(newMediumIds, projectId);
            }
        }
    }


    public APPResultMessage<Object, AppIntendedMediaProjectDTO> getIntendedMediaList(int userId, Short userType, Integer pageNum, Integer pageSize, Integer status, String keyword, Integer mediaPartyId) {
        MjNormalUser normalUser = normalUserMapper.selectByPrimaryKey(userId);
        // 根据用户查询出对应的媒体方，根据媒体方查询出对应的所有的媒体，因为分页原因，需要先查出项目，在根据每个项目获取其中没有失效的媒体
        if (normalUser == null || normalUser.getMediaPartyId() == null){
            return new APPResultMessage<>(6001, "该账户没有绑定媒体方");
        }
        if (normalUser.getUserType() != 5){
            return new APPResultMessage<>(6001, "无权限访问");
        }
        List<Integer> mediumIdList = mediumOfflineMapper.selectIdListByMediaPartyId(mediaPartyId);
        if (pageNum != null && pageSize != null){
            PageHelper.startPage(pageNum, pageSize);
            List<AppIntendedMediaProjectDTO> dtoList = projectIntendedMediaMapper.selectAppListByKeyword(mediumIdList, status, keyword);
            PageInfo<AppIntendedMediaProjectDTO> tables = new PageInfo<>(dtoList);
            for (AppIntendedMediaProjectDTO dto : tables.getList()){
                List<AppMediaListDTO> list = projectIntendedMediaMapper.selectAppListByProjectId(dto.getProjectId(), status, mediumIdList);
                dto.setMediaList(list);
            }
            ResultMessage result = ResultMessage.builder().setList(tables.getList()).setAllPageNumber(tables.getPages()).setCount(tables.getTotal());
            APPResultMessage<Object, AppIntendedMediaProjectDTO> message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        }else {
            List<AppIntendedMediaProjectDTO> dtoList = projectIntendedMediaMapper.selectAppListByKeyword(mediumIdList, status, keyword);
            for (AppIntendedMediaProjectDTO dto : dtoList){
                List<AppMediaListDTO> list = projectIntendedMediaMapper.selectAppListByProjectId(dto.getProjectId(), status, mediumIdList);
                dto.setMediaList(list);
            }
            ResultMessage result = ResultMessage.builder().setList(dtoList);
            APPResultMessage<Object, AppIntendedMediaProjectDTO> message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        }
    }

    public APPResultMessage doRejectIntendedMedia(int userId, String ids, String auditReason) {
        String s = sysLabelValueMapper.selectValueBySysIdAndReadOne(58);
        Integer monthNum = Integer.valueOf(s);
        Date endDate = DateUtil.getEndDate(new Date(), monthNum, 2);
        String[] split = ids.split(",");
        for (String id : split){
            ProjectIntendedMedia projectIntendedMedia = projectIntendedMediaMapper.selectByPrimaryKey(Integer.valueOf(id));
            projectIntendedMediaMapper.updateAuditReasonById(userId, projectIntendedMedia.getProjectId(), projectIntendedMedia.getMediumId(), auditReason, endDate);
        }
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doAcceptIntendedMedia(int userId, String ids) {
        String s = sysLabelValueMapper.selectValueBySysIdAndReadOne(58);
        Integer monthNum = Integer.valueOf(s);
        Date endDate = DateUtil.getEndDate(new Date(), monthNum, 2);
        List<ProjectIntendedMedia> mediaList = projectIntendedMediaMapper.selectAppNoAuditListByIds(ids.split(","));
        for (ProjectIntendedMedia intendedMedia : mediaList){
            projectIntendedMediaMapper.updateAcceptById(userId, intendedMedia.getProjectId(), intendedMedia.getMediumId(), endDate);
        }
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage<Object, MediaPartyDTO> getChooseMediumPartyList(int userId, short userType) {
        MjNormalUser normalUser = normalUserMapper.selectByPrimaryKey(userId);
        // 根据用户查询出对应的媒体方，根据媒体方查询出对应的所有的媒体，因为分页原因，需要先查出项目，在根据每个项目获取其中没有失效的媒体
        if (normalUser == null || normalUser.getMediaPartyId() == null){
            return new APPResultMessage<>(6001, "该账户没有绑定媒体方");
        }
        if (normalUser.getUserType() != 5){
            return new APPResultMessage<>(6001, "无权限访问");
        }
        List<MediaPartyDTO> list = mediaPartyMapper.selectListByIds(normalUser.getMediaPartyId().split(","));
        APPResultMessage message = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setList(list);
        message.setResult(resultMessage);
        return message;
    }

    public APPResultMessage<Object, MediaPartyDTO> doExportMediumParty(int userId, short userType, AppIntendedMediaExportReq req) {
        MjNormalUser normalUser = normalUserMapper.selectByPrimaryKey(userId);
        // 根据用户查询出对应的媒体方，根据媒体方查询出对应的所有的媒体，因为分页原因，需要先查出项目，在根据每个项目获取其中没有失效的媒体
        if (normalUser == null || normalUser.getMediaPartyId() == null){
            return new APPResultMessage<>(6001, "该账户没有绑定媒体方");
        }
        if (normalUser.getUserType() != 5){
            return new APPResultMessage<>(6001, "无权限访问");
        }
        List<Integer> mediumIdList = mediumOfflineMapper.selectIdListByMediaPartyIds(normalUser.getMediaPartyId().split(","));
        List<AppMediaExportDTO> list = projectIntendedMediaMapper.selectAppListByMediumIdList(mediumIdList);
        return APPResultMessage.getSuccessMessage();
    }
}
